<?php

/**
 * 订单商品售后数据统计
 * @author jc
 */
namespace app\statis\model;

use app\common\model\StatService;
use app\statis\lib\TimeStatistic;
use app\statis\model\CoreOrderModel;
use think\Exception;
use think\Model;

class StatServiceModel extends StatService
{
    /**
     * 订单商品售后统计
     *
     * @param string $stat_time 统计时间
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function summary($stat_time)
    {
        $coreM      = new CoreOrderModel();
        $start_time  = TimeStatistic::getStartTime($stat_time);
        $end_time   = TimeStatistic::getEndTime($stat_time);
        $stat_data  = [
            'stat_start_time'       => $start_time,
            'stat_end_time'         => $end_time,
            'stat_time'             => TimeStatistic::getStatTime($end_time),
            'order_num'             => 0, /*订单数量*/
            'total_amount'          => 0, /*订单总额，单价*数量*/
            'service_rate'          => 0, /*售后比率*/
            'service_product_num'   => 0, /*售后商品数*/
            'product_order_num'     => 0, /*商品订单总数*/
            'create_time'           => time(),
        ];

        /*获取统计数据*/
        $order_data = $coreM->getOrderByTime($start_time, $end_time);

        if (empty($order_data)) {
            if (!$id = $this->insertGetId($stat_data)) {
                throw new Exception('数据入库失败');
            }
            return;
        }
        /*进行相关统计：下单人数，下单数，订单总额等*/
        $stat_order                 = $this->calcOrder($order_data);
        /*组织数据*/
        $stat_data['order_num']     = $stat_order['order_num'];
        $stat_data['total_amount']  = (int)bcmul($stat_order['total_amount'], 100, 2);
        $stat_data['buyer_num']     = $stat_order['buyer_num'];
        /*统计入库*/
        if (!$id = $this->insertGetId($stat_data)) {
            throw new Exception('数据入库失败');
        }
    }


    /**
     * 计算订单统计
     * 相关的数据
     *
     * @param $order_data
     *
     * @return array
     */
    private function calcOrder($order_data)
    {
        $order_num      = 0;
        $buyer_num      = 0;
        $total_amount   = 0;
        $buyer_list     = [];

        foreach ($order_data as $k => $o) {
            $order_num += 1;
            $total_amount += $o['amount_product'];
            if (!isset($buyer_list[$o['user_id']])) {
                $buyer_list[$o['user_id']] = 0;
            }
            $buyer_list[$o['user_id']] += 1;
        }

        $buyer_num = count($buyer_list);

        $return = [
            'order_num'     => $order_num,
            'total_amount'  => $total_amount,
            'buyer_num'     => $buyer_num
        ];

        return $return;
    }

}